package com.example.javagobang.game;

import com.example.javagobang.model.MatchResponse;
import com.example.javagobang.model.Room;
import com.example.javagobang.model.UserInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.BitSet;
import java.util.LinkedList;
import java.util.Queue;
@Component
public class MatchQueue {
    private Queue<UserInfo> normalQueue = new LinkedList<>();
    private Queue<UserInfo> highQueue = new LinkedList<>();
    private Queue<UserInfo> veryHighQueue = new LinkedList<>();

    @Autowired
    private OnlineUser onlineUser;
    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private RoomManager roomManager;
    //添加进入匹配队列
    public void add(UserInfo userInfo){
        if(userInfo.getScore() < 1500){
            synchronized (normalQueue){
                normalQueue.add(userInfo);
                normalQueue.notify();
                System.out.println(userInfo.getUsername()+"进入了匹配队列");
            }

        }else if(userInfo.getScore() >= 1500 && userInfo.getScore() < 2000){
            synchronized (highQueue){
                highQueue.add(userInfo);
                highQueue.notify();
                System.out.println(userInfo.getUsername()+"进入了匹配队列");
            }

        }else {
            synchronized (veryHighQueue){
                veryHighQueue.add(userInfo);
                veryHighQueue.notify();
                System.out.println(userInfo.getUsername()+"进入了匹配队列");
            }

        }
    }
    //退出匹配队列
    public void remove(UserInfo userInfo){
        if(userInfo.getScore() < 1500){
            synchronized (normalQueue) {
                normalQueue.remove(userInfo);
                System.out.println(userInfo.getUsername()+"退出了匹配队列");
            }
        }else if(userInfo.getScore() >= 1500 && userInfo.getScore() < 2000){
            synchronized (highQueue){
                highQueue.remove(userInfo);
                System.out.println(userInfo.getUsername()+"退出了匹配队列");
            }

        }else {
            synchronized (veryHighQueue){
                veryHighQueue.remove(userInfo);
                System.out.println(userInfo.getUsername()+"退出了匹配队列");
            }
        }
    }

    public MatchQueue(){
         //线程扫描
        Thread t1 = new Thread(){
            @Override
            public void run(){
                while (true){
                    handlerMatch(normalQueue);
                }
            }
        };
        t1.start();
        Thread t2 = new Thread(){
            @Override
            public void run(){
                while (true){
                    handlerMatch(highQueue);
                }
            }
        };
        t2.start();
        Thread t3 = new Thread(){
            @Override
            public void run(){
                while (true){
                    handlerMatch(veryHighQueue);
                }
            }
        };
        t3.start();
    }

    private void handlerMatch(Queue<UserInfo> matchQueue) {
        synchronized (matchQueue){
            try {
                while (matchQueue.size() < 2){
                     //防止忙等
                    matchQueue.wait();
                }
                UserInfo player1 = matchQueue.poll();
                UserInfo player2 = matchQueue.poll();
                System.out.println("匹配出了两个玩家:" + player1.getUsername()+","+player2.getUsername());

                //获取两个玩家的websocket会话
                WebSocketSession session1 = onlineUser.getFromGameHall(player1.getUserId());
                WebSocketSession session2 = onlineUser.getFromGameHall(player2.getUserId());

                if(session1 == null){
                    matchQueue.offer(player2);
                    return;
                }
                if(session2 == null){
                    matchQueue.offer(player1);
                    return;
                }
                if(session1 == session2){
                    matchQueue.offer(player1);
                    return;
                }

                //添加到房间管理器中
                Room room = new Room();
                roomManager.add(room,player1.getUserId(),player2.getUserId());

                //最后反馈玩家，表示已经排到对手了
                MatchResponse response = new MatchResponse();
                response.setOk(true);
                response.setMessage("matchSuccess");
                String json1 = objectMapper.writeValueAsString(response);
                session1.sendMessage(new TextMessage(json1));

                MatchResponse response1 = new MatchResponse();
                response1.setOk(true);
                response1.setMessage("matchSuccess");
                String json2 = objectMapper.writeValueAsString(response1);
                session2.sendMessage(new TextMessage(json2));
            }catch (IOException | InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}
